// pages/index/index.js
Page({
  data: {
    socketStatus: 'closed',
    messages: []
  },

  // 连接 WebSocket
  connectSocket() {
    const that = this;
    
    wx.connectSocket({
      url: 'ws://127.0.0.1:7001/ws',
      success: () => {
        console.log('WebSocket连接成功');

        that.sendMessage('2222222222hello');

        that.setData({
          socketStatus: 'connecting'
        });
      }
    });

    // 监听 WebSocket 连接打开事件
    wx.onSocketOpen(function() {
      console.log('WebSocket连接已打开');
      that.setData({
        socketStatus: 'connected'
      });

      that.sendMessage('hello');
    });

    // 监听 WebSocket 接收到服务器的消息事件
    wx.onSocketMessage(function(res) {
      console.log('收到服务器内容：', res.data);
      const messages = that.data.messages;
      messages.push(JSON.parse(res.data));
      that.setData({
        messages
      });
    });

    // 监听 WebSocket 错误事件
    wx.onSocketError(function() {
      console.log('WebSocket连接打开失败');
      that.setData({
        socketStatus: 'failed'
      });
    });

    // 监听 WebSocket 连接关闭事件
    wx.onSocketClose(function() {
      console.log('WebSocket 已关闭');
      that.setData({
        socketStatus: 'closed'
      });
    });
  },

  // 发送消息
  sendMessage(msg) {
    if (this.data.socketStatus === 'connected') {
      wx.sendSocketMessage({
        data: msg,
        success: () => {
          console.log('消息发送成功');
        },
        fail: () => {
          console.log('消息发送失败');
        }
      });
    }
  },

  // 关闭 WebSocket 连接
  closeSocket() {
    wx.closeSocket({
      success: (res) => {
        console.log('WebSocket 已关闭');
      }
    });
  },

  onUnload() {
    // 页面卸载时关闭 WebSocket 连接
    this.closeSocket();
  }
});
